#include <string>
#include <unordered_map>
#include "log.hpp"
#include <fstream>
#include<iostream>
#include"inetaddr.hpp"

const std::string defaultpathname = "./dictionary.txt";
const std::string sep = ": ";

class Dictionary
{
public:
    Dictionary(const std::string &pathname = defaultpathname)
    : _pathname(pathname)
    {
    }

    ~Dictionary()
    {
    }

    bool Load()
    {
        std::ifstream in(_pathname);
        if (!in.is_open())
        {
            LOG(LogLevel::FATAL) << "file open error";
            return false;
        }
        std::string line;
        while(std::getline(in,line)) 
        {
            size_t pos = line.find(sep); 
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "找不到分隔符，解析失败" << line;
                continue;
            }       
            std::string chinese = line.substr(pos + sep.size());
            std::string english = line.substr(0,pos);
            if(chinese.empty() || english.empty())
            {
                LOG(LogLevel::WARNING) << "有空字符串，解析失败" << line;
                continue;
            }
            _dic.insert(std::make_pair(english,chinese));
            LOG(LogLevel::DEBUG)  << "加载成功" << line;
        }
        return true;
    }

    std::string Translate(const std::string& word,const InetAddr& client)
    {
        auto pos =  _dic.find(word);
        if(pos == _dic.end())
        {
            LOG(LogLevel::DEBUG) << "[" << client.GetIp()  << ":" << client.GetPort()  << "]# " << word << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "[" << client.GetIp()  << ":" << client.GetPort()  << "]# " << word << "->" << pos->second;
        return pos->second;
    }

private:
    std::string _pathname;
    std::unordered_map<std::string, std::string> _dic;
};